﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SimpleDatabaseAdapter
{
    internal class Serializer
    {
        internal static void SaveObject(object obj, string file)
        {
            string xml = GetXML(obj).Trim();
            File.WriteAllText(file, xml, Encoding.UTF8);
        }
        internal static string GetXML(object obj)
        {
            Type objType = obj.GetType();
            XmlSerializer writer = new XmlSerializer(objType);

            using (MemoryStream ms = new MemoryStream())
            {
                writer.Serialize(ms, obj);
                ms.Position = 0;
                StreamReader reader = new StreamReader(ms);
                string xml = reader.ReadToEnd();
                return xml;
            }
        }
        internal static string GetXMLClear(object obj)
        {
            string xml = GetXML(obj).Trim();

            string nextLine = "\r\n";
            if (xml.Contains(nextLine))
            {
                xml = xml.Substring(xml.IndexOf(nextLine) + nextLine.Length).Trim();
            }

            string tagOpen = "<";
            string tagClose = ">";
            string separator = " ";
            if (xml.StartsWith(tagOpen))
            {
                if (xml.Contains(tagClose))
                {
                    if (xml.Contains(separator))
                    {
                        if (xml.IndexOf(separator) < xml.IndexOf(tagClose))
                        {
                            xml = xml.Remove(xml.IndexOf(separator), xml.IndexOf(tagClose) - xml.IndexOf(separator));
                        }
                    }
                }
            }

            return xml;
        }
        internal static object ReadObject(string file, Type type)
        {
            string xml = File.ReadAllText(file);
            object obj = GetObject(xml, type);
            return obj;
        }
        internal static object GetObject(string xml, Type type)
        {
            XmlSerializer writer = new XmlSerializer(type);

            using (MemoryStream ms = new MemoryStream())
            {
                StreamWriter wr = new StreamWriter(ms);
                wr.Write(xml);
                wr.Flush();
                ms.Position = 0;

                object obj = writer.Deserialize(ms);
                return obj;
            }
        }
    }
}
